import { login, logout, getadminaccount } from '@/api/login'
import { getToken, setToken, removeToken ,setInfo} from '@/utils/auth'
import  Md5  from "js-md5";
import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      username: '',
      mobile:'',
      company_name:'',
      avatar: '',
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        return new Promise((resolve, reject) => {
          getadminaccount().then((res) => {
            const adminList = res.data.list
            const url = adminList.includes(userInfo.username) ? '/admin/login/dologin' : '/api/login/dologin'
            localStorage.setItem('adminInfo',adminList.includes(userInfo.username))
            // userInfo.password = Md5('huakun_'+userInfo.password)
            let data = JSON.parse(JSON.stringify(userInfo))
            data.password = Md5('huakun_'+userInfo.password)
            login(data, url).then(res => {
              const token = res.data.token || res.data.admintoken
              setToken(token)
              this.token = token
              const data = JSON.stringify(res.data)
              setInfo(data)
              resolve()
            }).catch(error => {
              reject(error)
            })
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.user
            const avatar = (user.avatar == "" || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;

            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.name = user.userName
            this.avatar = avatar;
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          const adminInfo = localStorage.getItem('adminInfo')
          const url = adminInfo == 'true' ? '/admin/login/dologinout':'/api/login/dologinout'
          logout(url).then(() => {
            this.token = ''
            // this.roles = []
            // this.permissions = []
            localStorage.clear()
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    }
  })

export default useUserStore
